define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'merchant/index' + location.search,
                    add_url: 'merchant/add',
                    edit_url: 'merchant/edit',
                    del_url: 'merchant/del',
                    multi_url: 'merchant/multi',
                    import_url: 'merchant/import',
                    table: 'merchant',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'merchant_id', title: '商家ID', operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'store_name', title: '店铺名称', operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'phone', title: '联系电话', operate: 'LIKE'},
                        {field: 'address', title: '地址', operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {
                            field: 'status', 
                            title: '状态', 
                            searchList: {"1": "正常", "0": "禁用"}, 
                            formatter: function(value, row, index) {
                                var colorArray = {1: 'success', 0: 'danger'};
                                var textArray = {1: '正常', 0: '禁用'};
                                return '<span class="label label-' + colorArray[value] + '">' + textArray[value] + '</span>';
                            }
                        },
                        {
                            field: 'verification_status', 
                            title: '认证状态', 
                            searchList: {"0": "未认证", "1": "已认证", "2": "认证失败"}, 
                            formatter: function(value, row, index) {
                                var colorArray = {0: 'default', 1: 'success', 2: 'danger'};
                                var textArray = {0: '未认证', 1: '已认证', 2: '认证失败'};
                                if (value == 0) {
                                    // 未认证状态使用自定义样式，确保有明显的背景色
                                    return '<span class="label" style="background-color: #95a5a6; color: white; padding: 3px 6px; border-radius: 3px;">' + textArray[value] + '</span>';
                                }
                                return '<span class="label label-' + colorArray[value] + '">' + textArray[value] + '</span>';
                            }
                        },
                        {
                            field: 'disable_reason_text', 
                            title: '禁用原因', 
                            operate: 'LIKE',
                            table: table, 
                            class: 'autocontent', 
                            formatter: function(value, row, index) {
                                if (row.status == 0 && value) {
                                    return '<span class="text-warning" style="color: #f39c12;" title="' + value + '">' + (value.length > 20 ? value.substring(0, 20) + '...' : value) + '</span>';
                                }
                                return '-';
                            }
                        },
                        {field: 'created_at', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'last_login_time', title: '最后登录', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', 
                            title: __('Operate'), 
                            table: table, 
                            events: Table.api.events.operate, 
                            formatter: function (value, row, index) {
                                var that = this;
                                var table = $(that.table).clone(true);
                                $(table).data("operate-edit", null);
                                $(table).data("operate-del", null);
                                
                                var buttons = [];
                                
                                // 查看详情按钮
                                buttons.push('<a href="javascript:;" class="btn btn-xs btn-info btn-detail" data-id="' + row.id + '" title="查看详情"><i class="fa fa-eye"></i></a>');
                                
                                // 启用/禁用按钮
                                if (row.status == 1) {
                                    buttons.push('<a href="javascript:;" class="btn btn-xs btn-warning btn-toggle" data-id="' + row.id + '" title="禁用"><i class="fa fa-toggle-off"></i></a>');
                                } else {
                                    buttons.push('<a href="javascript:;" class="btn btn-xs btn-success btn-toggle" data-id="' + row.id + '" title="启用"><i class="fa fa-toggle-on"></i></a>');
                                }
                                
                                // 重置密码按钮
                                buttons.push('<a href="javascript:;" class="btn btn-xs btn-danger btn-reset-password" data-id="' + row.id + '" title="重置密码"><i class="fa fa-key"></i></a>');
                                
                                return buttons.join(' ');
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 查看详情
            $(document).on('click', '.btn-detail', function () {
                var id = $(this).data('id');
                Fast.api.open('merchant/detail?ids=' + id, '商家详情', {
                    area: ['800px', '600px']
                });
            });
            
            // 启用/禁用
            $(document).on('click', '.btn-toggle', function () {
                var id = $(this).data('id');
                var $btn = $(this);
                var isDisable = $btn.hasClass('btn-warning'); // 如果是橙色按钮，说明是要禁用
                
                if (isDisable) {
                    // 禁用商家，需要填写原因
                    Layer.prompt({
                        title: '禁用商家 - 请填写禁用原因4个字',
                        formType: 2, // 多行文本框
                        value: '',
                        area: ['400px', '200px'],
                        maxlength: 500,
                        placeholder: '请输入禁用原因4个字（必填）'
                    }, function(value, index) {
                        if (!value || value.trim() === '') {
                            Toastr.error('禁用原因不能为空');
                            return false;
                        }
                        
                        Fast.api.ajax({
                            url: 'merchant/toggle',
                            data: {ids: id, reason: value.trim()}
                        }, function(data, ret){
                            table.bootstrapTable('refresh');
                            Toastr.success(ret.msg);
                            Layer.close(index);
                        });
                    });
                } else {
                    // 启用商家，显示确认弹窗
                    // 获取当前行数据
                    var $tr = $btn.closest('tr');
                    var index = $tr.data('index');
                    var rowData = table.bootstrapTable('getData')[index];
                    
                    // 格式化禁用时间
                    var disabledTime = rowData && rowData.disabled_at_text ? rowData.disabled_at_text : '未知时间';
                    
                    // 获取禁用原因
                    var disableReason = rowData && rowData.disable_reason_text ? rowData.disable_reason_text : '无禁用原因记录';
                    
                    Layer.prompt({
                        title: '恢复使用',
                        content: '<div style="padding: 20px; text-align: center;">' +
                                '<h3 style="margin-bottom: 20px;">是否恢复商家账号使用？</h3>' +
                                '<div style="margin-bottom: 15px; text-align: left;">' +
                                '<div style="margin-bottom: 8px;"><strong>禁用时间：</strong> ' + disabledTime + '</div>' +
                                // '<div style="margin-bottom: 8px;"><strong>操作者：</strong> ' + currentAdmin + '</div>' +
                                '<div style="margin-bottom: 15px;"><strong>禁用原因：</strong> ' + disableReason + '</div>' +
                                '</div>' +
                                '<div style="margin-bottom: 15px; text-align: left;">' +
                                '<label for="recovery-reason" style="display: block; margin-bottom: 5px;"><strong>* 恢复原因：</strong></label>' +
                                '<textarea id="recovery-reason" placeholder="请输入恢复原因..." style="width: 100%; height: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;" maxlength="100"></textarea>' +
                                '<div style="text-align: right; color: #999; font-size: 12px; margin-top: 5px;"><span id="char-count">0</span>/100</div>' +
                                '</div>' +
                                '</div>',
                        area: ['500px', '400px'],
                        btn: ['取消', '确定'],
                        yes: function(index) {
                            Layer.close(index);
                        },
                        btn2: function(index) {
                            var reason = $('#recovery-reason').val().trim();
                            if (!reason) {
                                Toastr.error('恢复原因不能为空');
                                return false;
                            }
                            
                            Fast.api.ajax({
                                url: 'merchant/toggle',
                                data: {ids: id, recovery_reason: reason}
                            }, function(data, ret){
                                table.bootstrapTable('refresh');
                                Toastr.success(ret.msg);
                                Layer.close(index);
                            });
                        }
                    });
                    
                    // 添加字符计数功能
                    setTimeout(function() {
                        $('#recovery-reason').on('input', function() {
                            var length = $(this).val().length;
                            $('#char-count').text(length);
                        });
                    }, 100);
                }
            });
            
            // 重置密码
            $(document).on('click', '.btn-reset-password', function () {
                var id = $(this).data('id');
                Fast.api.open('merchant/resetPassword?ids=' + id, '重置密码', {
                    area: ['500px', '300px']
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            // 详情页面不需要特殊处理
        },
        resetPassword: function () {
            Form.api.bindevent($("#reset-password-form"));
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});